﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using NReader.Model.RAS;
using NReader.Service;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using XnReader.WinRT.Common;
using XnReader.WinRT.Controlx;

// “基本页”项模板在 http://go.microsoft.com/fwlink/?LinkId=234237 上有介绍

namespace XnReader.WinRT.Forms
{
    /// <summary>
    /// 基本页，提供大多数应用程序通用的特性。
    /// </summary>
    public sealed partial class BookcaseModify : XnReader.WinRT.Common.LayoutAwarePage
    {
        /// <summary>
        /// 默认显示的第一个书架编号
        /// </summary>
        private int _bookcaseId = 1;

        public BookcaseModify()
        {
            InitializeComponent();
            var visiblesFooter = new CommandInfo
                                     {
                                         Theme = "white",
                                         VisibleDelete = Visibility.Visible,
                                         VisibleClean = Visibility.Visible
                                     };
            if (footer != null)
            {
                footer.DataContext = visiblesFooter;
                footer.CleanClickEvent += FooterCleanClickEvent;
                footer.DeleteClickEvent += FooterDeleteClickEvent;
            }
        }

        /// <summary>
        /// 清空书架
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async void FooterCleanClickEvent(object sender, RoutedEventArgs e)
        {
            if ((itemGridView.Visibility == Visibility.Visible && itemGridView.Items.Count == 0) ||
                (itemListView.Visibility == Visibility.Visible && itemListView.Items.Count == 0))
                return;

            var messageDialog = new MessageDialog("确定清空当前书架的所有书籍?");
            messageDialog.Commands.Add(new UICommand("确定", new UICommandInvokedHandler(CommandInvokedHandler)));
            messageDialog.Commands.Add(new UICommand("取消", new UICommandInvokedHandler(CommandInvokedHandler)));
            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;
            await messageDialog.ShowAsync();
        }

        /// <summary>
        /// 删除选中书籍
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async void FooterDeleteClickEvent(object sender, RoutedEventArgs e)
        {
            if ((itemGridView.Visibility == Visibility.Visible && itemGridView.SelectedItems.Count == 0) ||
               (itemListView.Visibility == Visibility.Visible && itemListView.SelectedItems.Count == 0))
                return;

            var messageDialog = new MessageDialog("确定删除当前选中的所有书籍?");
            messageDialog.Commands.Add(new UICommand("确定", new UICommandInvokedHandler(CommandDeleteInvokedHandler)));
            messageDialog.Commands.Add(new UICommand("取消", new UICommandInvokedHandler(CommandDeleteInvokedHandler)));
            messageDialog.DefaultCommandIndex = 0;
            messageDialog.CancelCommandIndex = 1;
            await messageDialog.ShowAsync();
        }

        #region Commands
        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private async void CommandInvokedHandler(IUICommand command)
        {
            if (command.Label.Equals("确定"))
            {
                await DeleteFromBookcase(true);
            }
        }

        /// <summary>
        /// Callback function for the invocation of the dialog commands.
        /// </summary>
        /// <param name="command">The command that was invoked.</param>
        private async void CommandDeleteInvokedHandler(IUICommand command)
        {
            if (command.Label.Equals("确定"))
            {
                await DeleteFromBookcase(false);
            }
        }

        #endregion

        /// <summary>
        /// 从书架删除书籍
        /// </summary>
        /// <param name="isAll">全部删除</param>
        /// <returns></returns>
        private async Task DeleteFromBookcase(bool isAll)
        {
            IList<object> selectedItems;
            if(itemGridView.Visibility==Visibility.Visible)
            {
                selectedItems = isAll ? itemGridView.Items : itemGridView.SelectedItems;
            }
            else
            {
                 selectedItems = isAll ? itemListView.Items : itemListView.SelectedItems; 
            }

            string errors = "";
            if (selectedItems != null && selectedItems.Count > 0)
            {
                foreach (ArticleInfo article in selectedItems)
                {
                    //本地文件，先删除文件后删除数据库
                    if (article.online.Equals(0))
                    {
                        try
                        {
                            var result =
                                await
                                ArticleService.Instance().DeleteDocument(string.Format("{0}{1}", article.articlename,
                                                                                       article.articletype));
                            if (!string.IsNullOrEmpty(result)) //删除资料失败
                            {
                                errors += string.Format("{0},异常信息:{1}", article.articlename, result);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            errors += string.Format("{0},异常信息:{1}", article.articlename, ex.Message);
                            continue;
                            // throw;
                        }
                    }
                    if (!await ArticleService.Instance().DeleteBookStore(article.articleid) ||
                        !await ArticleService.Instance().DeleteBook(article))
                    {
                        errors += string.Format("{0},数据异常", article.articlename);
                    }
                }
            }
            else
            {
            }
            if (!string.IsNullOrEmpty(errors))
            {
                var md = new MessageDialog(errors);
                await md.ShowAsync();
            }
            DataBinding();
            BottomAppBar.IsOpen = false;
        }

        /// <summary>
        /// 使用在导航过程中传递的内容填充页。在从以前的会话
        /// 重新创建页时，也会提供任何已保存状态。
        /// </summary>
        /// <param name="navigationParameter">最初请求此页时传递给
        /// <see cref="Frame.Navigate(Type, Object)"/> 的参数值。
        /// </param>
        /// <param name="pageState">此页在以前会话期间保留的状态
        /// 字典。首次访问页面时为 null。</param>
        protected async override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            var bookcaseId = navigationParameter.ToString();
            if (!string.IsNullOrEmpty(bookcaseId))
            {
                _bookcaseId = int.Parse(bookcaseId);
                DataBinding();
            }
        }

        private async void DataBinding()
        {
            var bookcase = await NReader.Service.ArticleService.Instance().GetBookcase(_bookcaseId);
            if (bookcase != null)
            {
                txtHeader.Text = string.Format("编辑{0}", bookcase.casename);
                txtCount.Text = string.Format("({0}/{1})", bookcase.total, 30);
                var list = await ArticleService.Instance().GetBookStoreLocal(_bookcaseId);
                DefaultViewModel["ArticleList"] = list;
                cvsArticleList.Source = list;
            }
        }

        /// <summary>
        /// 保留与此页关联的状态，以防挂起应用程序或
        /// 从导航缓存中放弃此页。值必须符合
        /// <see cref="SuspensionManager.SessionState"/> 的序列化要求。
        /// </summary>
        /// <param name="pageState">要使用可序列化状态填充的空字典。</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {

        }

        private void ItemGridViewSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (itemGridView.Visibility == Visibility.Visible)
            {
                BottomAppBar.IsOpen = itemGridView.SelectedItems.Count > 0;
            }
            else
            {
                BottomAppBar.IsOpen = itemListView.SelectedItems.Count > 0;
            }
        }
    }
}
